/****************************播放列表相关***********************************/
var loadedFavCount = 0;

window.handleHashResponse_fav_search = function (data) {
    // 每次拿到一条数据就插入一行
    const listElement = document.getElementById('music_list');
    var row = listElement.insertRow(-1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    music_hash[loadedFavCount+1] = data.hash;                    //解决了删除收藏的错位问题，没解决此处的异步问题
    cell1.innerHTML = ++loadedFavCount;
    var fileName = data.fileName;
    var songName = fileName.slice(data.author_name.length+2,fileName.length);
    cell2.innerHTML = songName;
    cell3.innerHTML = data.author_name;
    cell5.innerHTML = `<button id="love_but${loadedFavCount}" style="background-color: transparent; cursor:pointer; border: none;" class="fa fa-heart" onclick="love_song(${loadedFavCount},1)"></button>`;
        

    row.ondblclick = function () {
        console.log(`当前双击的音乐的 hash: ${data.hash}`);
        // 动态加载歌曲信息
        const hash_script = document.createElement('script');
        currentIndex = loadedFavCount;
        hash_script.src = `http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&format=jsonp&hash=${encodeURIComponent(data.hash)}&callback=handleHashResponse`;
        http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&format=jsonp&hash=
        document.body.appendChild(hash_script);
        // 清理脚本
        hash_script.onload = () => document.body.removeChild(hash_script);
    };
};

function my_musiclist() {
    loadedFavCount = 0; 
    const listElement = document.getElementById('music_list');
    // 清空表格（保留表头）
    for (let i = listElement.rows.length - 1; i > 0; i--) {
        listElement.deleteRow(i);
    }
    
    const favorites = getCookie("favorites") || "[]";
    const favoritesList = JSON.parse(favorites);

    for (let i = 0; i < favoritesList.length; i++) {
        const hash_script = document.createElement('script');
        hash_script.src = `http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&format=jsonp&hash=${encodeURIComponent(favoritesList[i])}&callback=handleHashResponse_fav_search`;
        document.body.appendChild(hash_script);
    }
}


function love_song(i, j) {
    var btn = document.getElementById(`love_but${i}`);
    if (j == 0) {
        btn.className = "fa fa-heart";
        btn.setAttribute("onclick", `love_song(${i},1)`);
        showFavToast("音乐已收藏");

        const favorites = getCookie("favorites") || "[]";
        const favoritesList = JSON.parse(favorites);
        if (!favoritesList.includes(music_hash[i].toLowerCase())) {
            favoritesList.push(music_hash[i].toLowerCase());
            // 更新 Cookie（有效期1年）
            document.cookie = `favorites=${JSON.stringify(favoritesList)}; expires=${new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toUTCString()}; path=/`;
            console.log(document.cookie);
        }
    }

    else if (j == 1) {
        btn.className = "fa fa-heart-o";

        const favorites = getCookie("favorites") || "[]";
        const favoritesList = JSON.parse(favorites);
        if (favoritesList.includes(music_hash[i].toLowerCase())) {
            const idx = favoritesList.indexOf(music_hash[i].toLowerCase());
            if (idx > -1) {
                favoritesList.splice(idx, 1);
            }
            // 更新 Cookie（有效期1年）
            document.cookie = `favorites=${JSON.stringify(favoritesList)}; expires=${new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toUTCString()}; path=/`;
            console.log(document.cookie);
        }

        btn.setAttribute("onclick", `love_song(${i},0)`);
        showFavToast("已取消收藏");
    }

    // 弹窗提示函数
    function showFavToast(msg) {
        var toast = document.getElementById('fav-toast');
        toast.innerText = msg;
        toast.style.display = "block";
        setTimeout(() => {         //入
            toast.style.opacity = 1;
        }, 10); // 触发过渡
        setTimeout(() => {          //出
            toast.style.opacity = 0;
            setTimeout(() => {
                toast.style.display = "none";
            }, 500); // 等待淡出动画结束
        }, 2000);
    }
}